<template>
  <div>
    <i-dialog
      :title="row.deviceId ? '编辑SN编码' : '绑定SN编码'"
      :visible="visible"
      width="642px"
      :close-on-click-modal="false"
      @close="outerClose"
    >
      <i-form
        :items="formItems"
        :model="form"
        ref="form"
        :rules="rules"
        label-width="95px"
        class="demo-form"
      >
      </i-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="outerClose">取 消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </span>
    </i-dialog>
  </div>
</template>
<script>
import { snCodeBind, snCodeUpdate } from '@/api/device'
import formValidate from '@/utils/validate'
export default {
  name: 'AddSNDevice',
  data() {
    return {
      form: {},
      formItems: [
        {
          type: 'text',
          value: 'deviceNum',
          label: '设备号',
          clearable: true,
          required: true,
        },
        {
          type: 'text',
          value: 'snCode',
          label: 'SN编码',
          clearable: true,
          required: true,
        },
      ],
      rules: {
        deviceNum: [
          {
            max: 32,
            message: '最多允许输入32个字符',
            trigger: ['change', 'blur'],
          },
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        snCode: [
          {
            max: 100,
            message: '最多允许输入100个字符',
            trigger: ['change', 'blur'],
          },
          {
            validator: formValidate('validateLettersAndNumbers'),
            trigger: ['change', 'blur'],
          },
        ],
      },
    }
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    row: {
      type: Object,
      default: () => {},
    },
  },
  mounted() {
    this.form = {
      deviceNum: this.row.deviceNum,
      snCode: this.row.snCode,
    }
  },
  methods: {
    outerClose() {
      this.$emit('update:visible', false)
    },
    refreshTable() {
      this.$emit('refreshTable')
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = {
            ...this.form,
            id: this.row.id, //编辑的时候需要
          }
          ;(this.row.id ? snCodeUpdate : snCodeBind)(params).then(() => {
            this.$message({
              message: this.row.id ? '编辑成功' : '添加成功',
              type: 'success',
            })
            this.refreshTable()
            this.outerClose()
          })
        }
      })
    },
  },
}
</script>
